/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen;

import java.sql.*;
import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.*;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import resources.local_connection;

       
/**
 *
 * @author Homeroe
 */
public class imagenFacturas extends javax.swing.JFrame {

    // Globales
    
    static Connection con;
    boolean[] hayImagen = new boolean[2];
    
    private Image ConvertirImagen(byte[] bytes,String ext) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator readers = ImageIO.getImageReadersByFormatName(ext);
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; // File or InputStream
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        return reader.read(0, param);
    } 

    /**
     * Creates new form mainWindow
     * @throws java.io.IOException
     */
    public imagenFacturas() throws IOException {
        initComponents();
        try {
            int i=0;
            // Preparamos la conexion a la BD y checamos si ya exita una imagen
            con = local_connection.getconnect();
            PreparedStatement st = (PreparedStatement)con.prepareStatement("SELECT * FROM archivos WHERE id=405 OR id=406");
            ResultSet rs = st.executeQuery();
            while(rs.next()) {
                String ext = rs.getString("ext");
                Image img = ConvertirImagen(rs.getBytes("archivo"),ext);
                Image resized = img.getScaledInstance(150, 150, 10);
                ImageIcon icon = new ImageIcon(resized);
                switch(i){
                    case 0: imagen.setIcon(icon); break;
                    case 1: imagen2.setIcon(icon); break;
                }
                hayImagen[i]=true; 
                i++;
            }                
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileChooser = new javax.swing.JFileChooser();
        abrirImagen = new javax.swing.JButton();
        imagen = new javax.swing.JLabel();
        upload = new javax.swing.JButton();
        label_QR = new javax.swing.JLabel();
        buttonCancelar = new javax.swing.JButton();
        imagen2 = new javax.swing.JLabel();
        abrirImagen2 = new javax.swing.JButton();
        label_QR1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Carga de Imagen QR");
        setIconImage(new ImageIcon(getClass().getResource("/resources/logo_rayito.png")).getImage());
        setResizable(false);

        abrirImagen.setText("Abrir Imagen");
        abrirImagen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                abrirImagenActionPerformed(evt);
            }
        });

        imagen.setBackground(new java.awt.Color(153, 153, 153));
        imagen.setForeground(new java.awt.Color(102, 102, 102));
        imagen.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        upload.setText("Guardar");
        upload.setEnabled(false);
        upload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uploadActionPerformed(evt);
            }
        });

        label_QR.setText("Imagen de Factura");

        buttonCancelar.setText("Cancelar");
        buttonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelarActionPerformed(evt);
            }
        });

        imagen2.setBackground(new java.awt.Color(153, 153, 153));
        imagen2.setForeground(new java.awt.Color(102, 102, 102));
        imagen2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        abrirImagen2.setText("Abrir Imagen");
        abrirImagen2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                abrirImagen2ActionPerformed(evt);
            }
        });

        label_QR1.setText("Imagen de Logo ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(abrirImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                        .addComponent(abrirImagen2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(label_QR)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(label_QR1)
                        .addGap(38, 38, 38))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(imagen, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(imagen2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(buttonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(upload, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label_QR)
                    .addComponent(label_QR1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(abrirImagen2)
                    .addComponent(abrirImagen, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(imagen, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(imagen2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonCancelar)
                    .addComponent(upload))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void abrirImagenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_abrirImagenActionPerformed
        FileNameExtensionFilter filtro = new FileNameExtensionFilter(
        "JPG, PNG & GIF", "jpg", "gif", "jpeg", "png");
        fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
        fileChooser.setFileFilter(filtro);
        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                Image img = ImageIO.read(fileChooser.getSelectedFile());
                Image resized = img.getScaledInstance(150, 150, 10);
                ImageIcon icon = new ImageIcon(resized);
                imagen.setIcon(icon);
                upload.setEnabled(true);
            } catch (IOException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);            }
        }
    }//GEN-LAST:event_abrirImagenActionPerformed

    private void uploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadActionPerformed
        try {
            // Preparamos el archivo para subirlo a la BD
            File file = fileChooser.getSelectedFile();
            FileInputStream fis = new FileInputStream(file);
            // Preparamos el query a la BD
            PreparedStatement st;
            // Da error al usar triple '/'. Sin embargo es regex valido...
            String ext = file.getName().split("\\.")[1];
            // Aqui guardamos el mensaje de noticia
            String noticeText = "<html><font color='green'>";
            // Comprobamos si ya exite un registro de imagen QR, si la hay, la actualiza
            if(!hayImagen[0]){
                st = (PreparedStatement)con.prepareStatement("INSERT INTO imagenes(img_id,imagenes,extension) VALUES(0,?,?)");
                st.setBinaryStream(1, fis, (int) file.length());
                st.setString(2, ext);
                st.execute();
                noticeText += "Imagen Creada<br/>";
            } else {
                st = (PreparedStatement)con.prepareStatement("UPDATE imagenes SET imagenes=?,extension=? WHERE img_id = 0");
                st.setBinaryStream(1, fis, (int) file.length());
                st.setString(2, ext);
                st.execute();
                noticeText += "Imagen actualizada<br/>";
            }
        } catch (SQLException | FileNotFoundException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }//GEN-LAST:event_uploadActionPerformed

    private void buttonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_buttonCancelarActionPerformed

    private void abrirImagen2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_abrirImagen2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_abrirImagen2ActionPerformed

    /**
     * @param args the command line arguments
     */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton abrirImagen;
    private javax.swing.JButton abrirImagen2;
    private javax.swing.JButton buttonCancelar;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JLabel imagen;
    private javax.swing.JLabel imagen2;
    private javax.swing.JLabel label_QR;
    private javax.swing.JLabel label_QR1;
    private javax.swing.JButton upload;
    // End of variables declaration//GEN-END:variables
}
